import type { Directive } from "vue";

export default {
  mounted(el, binding) {

    let startX = 0;
    let startY = 0;
    let initialLeft = 0;
    let initialTop = 0;

    const titleEl = el.querySelector('.overlay-header') as HTMLElement; // 获取标题部分

    // 如果没有标题部分，直接返回
    if (!titleEl) return;

    const onMouseDown = (e: MouseEvent) => {
      const enabled = binding.value.enabled
      if (!enabled) return;
      if (!enabled()) return;
      startX = e.clientX;
      startY = e.clientY;
      initialLeft = parseInt(el.style.left || '0', 10);
      initialTop = parseInt(el.style.top || '0', 10);

      document.addEventListener('mousemove', onMouseMove);
      document.addEventListener('mouseup', onMouseUp);
    };

    const onMouseMove = (e: MouseEvent) => {
      const deltaX = e.clientX - startX;
      const deltaY = e.clientY - startY;
      el.style.left = `${initialLeft + deltaX}px`;
      el.style.top = `${initialTop + deltaY}px`;
    };

    const onMouseUp = () => {
      document.removeEventListener('mousemove', onMouseMove);
      document.removeEventListener('mouseup', onMouseUp);

      // 如果有回调函数，触发回调
      if (binding.value && binding.value.onMove) {
        binding.value.onMove(parseInt(el.style.left), parseInt(el.style.top));
      }
    };

    // 绑定事件监听器到标题部分
    titleEl.addEventListener('mousedown', onMouseDown);
  }
} as Directive<HTMLElement>;
